

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta name="referrer" content="no-referrer" />
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/apple-touch-icon.png">
  <link rel="icon" href="/img/fyy.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="fyy-coding">
  <meta name="keywords" content="">
  
    <meta name="description" content="FutureFuture 类有什么用？Future 类是异步思想的典型运用，主要用在一些需要执行耗时任务的场景，避免程序一直原地等待耗时任务执行完成，执行效率太低。具体来说是这样的：当我们执行某一耗时的任务时，可以将这个耗时任务交给一个子线程去异步执行，同时我们可以干点其他事情，不用傻傻等待耗时任务执行完成。等我们的事情干完后，我们再通过 Future 类获取到耗时任务的执行结果。这样一来，程序的">
<meta property="og:type" content="article">
<meta property="og:title" content="CompletableFuture">
<meta property="og:url" content="http://example.com/2021/04/06/JUC/CompletableFuture/index.html">
<meta property="og:site_name" content="fyy-coding">
<meta property="og:description" content="FutureFuture 类有什么用？Future 类是异步思想的典型运用，主要用在一些需要执行耗时任务的场景，避免程序一直原地等待耗时任务执行完成，执行效率太低。具体来说是这样的：当我们执行某一耗时的任务时，可以将这个耗时任务交给一个子线程去异步执行，同时我们可以干点其他事情，不用傻傻等待耗时任务执行完成。等我们的事情干完后，我们再通过 Future 类获取到耗时任务的执行结果。这样一来，程序的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231015211855815.png">
<meta property="article:published_time" content="2021-04-06T04:13:33.000Z">
<meta property="article:modified_time" content="2024-03-18T11:54:56.937Z">
<meta property="article:author" content="fyy">
<meta property="article:tag" content="JUC">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="c:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231015211855815.png">
  
  
  
  <title>CompletableFuture - fyy-coding</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.7","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","app_key":"96APiPOtZEiCQlv5h3jjZfbC","server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  
    <!-- Google tag (gtag.js) -->
    <script async>
      if (!Fluid.ctx.dnt) {
        Fluid.utils.createScript("https://www.googletagmanager.com/gtag/js?id=", function() {
          window.dataLayer = window.dataLayer || [];
          function gtag() {
            dataLayer.push(arguments);
          }
          gtag('js', new Date());
          gtag('config', '');
        });
      }
    </script>
  

  

  

  

  
    
  



  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>fyy-coding</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/" target="_self">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/" target="_self">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/" target="_self">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/" target="_self">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/" target="_self">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="CompletableFuture"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-04-06 12:13" pubdate>
          2021年4月6日 中午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          4.5k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          38 分钟
        
      </span>
    

    
    
      
        <span id="leancloud-page-views-container" class="post-meta" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="leancloud-page-views"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">CompletableFuture</h1>
            
            
              <div class="markdown-body">
                
                <h3 id="Future"><a href="#Future" class="headerlink" title="Future"></a>Future</h3><h4 id="Future-类有什么用？"><a href="#Future-类有什么用？" class="headerlink" title="Future 类有什么用？"></a>Future 类有什么用？</h4><p><code>Future</code> 类是异步思想的典型运用，主要用在一些需要执行耗时任务的场景，避免程序一直原地等待耗时任务执行完成，执行效率太低。具体来说是这样的：当我们执行某一耗时的任务时，可以将这个耗时任务交给一个子线程去异步执行，同时我们可以干点其他事情，不用傻傻等待耗时任务执行完成。等我们的事情干完后，我们再通过 <code>Future</code> 类获取到耗时任务的执行结果。这样一来，程序的执行效率就明显提高了。</p>
<p>这其实就是多线程中经典的 <strong>Future 模式</strong>，你可以将其看作是一种设计模式，核心思想是异步调用，主要用在多线程领域，并非 Java 语言独有。</p>
<p>在 Java 中，<code>Future</code> 类只是一个泛型接口，位于 <code>java.util.concurrent</code> 包下，其中定义了 5 个方法，主要包括下面这 4 个功能：</p>
<ul>
<li>取消任务；</li>
<li>判断任务是否被取消;</li>
<li>判断任务是否已经执行完成;</li>
<li>获取任务执行结果。</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// V 代表了Future执行的任务返回值的类型</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Future</span>&lt;V&gt; &#123;<br>    <span class="hljs-comment">// 取消任务执行</span><br>    <span class="hljs-comment">// 成功取消返回 true，否则返回 false</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-title function_">cancel</span><span class="hljs-params">(<span class="hljs-type">boolean</span> mayInterruptIfRunning)</span>;<br>    <span class="hljs-comment">// 判断任务是否被取消</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-title function_">isCancelled</span><span class="hljs-params">()</span>;<br>    <span class="hljs-comment">// 判断任务是否已经执行完成</span><br>    <span class="hljs-type">boolean</span> <span class="hljs-title function_">isDone</span><span class="hljs-params">()</span>;<br>    <span class="hljs-comment">// 获取任务执行结果</span><br>    V <span class="hljs-title function_">get</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> InterruptedException, ExecutionException;<br>    <span class="hljs-comment">// 指定时间内没有返回计算结果就抛出 TimeOutException 异常</span><br>    V <span class="hljs-title function_">get</span><span class="hljs-params">(<span class="hljs-type">long</span> timeout, TimeUnit unit)</span> <span class="hljs-keyword">throws</span> InterruptedException, ExecutionException, TimeoutException<br>&#125;<br></code></pre></td></tr></table></figure>

<p>简单理解就是：我有一个任务，提交给了 <code>Future</code> 来处理。任务执行期间我自己可以去做任何想做的事情。并且，在这期间我还可以取消任务以及获取任务的执行状态。一段时间之后，我就可以 <code>Future</code> 那里直接取出任务执行结果。</p>
<h2 id="CompletableFuture"><a href="#CompletableFuture" class="headerlink" title="CompletableFuture"></a>CompletableFuture</h2><p><code>Future</code> 在实际使用过程中存在一些局限性比如不支持异步任务的编排组合、获取计算结果的 <code>get()</code> 方法为阻塞调用。</p>
<p>Java 8 才被引入<code>CompletableFuture</code> 类可以解决<code>Future</code> 的这些缺陷。<code>CompletableFuture</code> 除了提供了更为好用和强大的 <code>Future</code> 特性之外，还提供了函数式编程、异步任务编排组合（可以将多个异步任务串联起来，组成一个完整的链式调用）等能力。</p>
<p>下面我们来简单看看 <code>CompletableFuture</code> 类的定义。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">CompletableFuture</span>&lt;T&gt; <span class="hljs-keyword">implements</span> <span class="hljs-title class_">Future</span>&lt;T&gt;, CompletionStage&lt;T&gt; &#123;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>CompletableFuture</code> 同时实现了 <code>Future</code> 和 <code>CompletionStage</code> 接口。</p>
<p><code>CompletionStage</code> 接口描述了一个异步计算的阶段。很多计算可以分成多个阶段或步骤，此时可以通过它将所有步骤组合起来，形成异步计算的流水线。</p>
<p><code>CompletableFuture</code> 除了提供了更为好用和强大的 <code>Future</code> 特性之外，还提供了函数式编程的能力。</p>
<p><code>Future</code> 接口有 5 个方法：</p>
<ul>
<li><code>boolean cancel(boolean mayInterruptIfRunning)</code>：尝试取消执行任务。</li>
<li><code>boolean isCancelled()</code>：判断任务是否被取消。</li>
<li><code>boolean isDone()</code>：判断任务是否已经被执行完成。</li>
<li><code>get()</code>：等待任务执行完成并获取运算结果。</li>
<li><code>get(long timeout, TimeUnit unit)</code>：多了一个超时时间。</li>
</ul>
<p><code>CompletionStage</code> 接口中的方法比较多，<code>CompletableFuture</code> 的函数式能力就是这个接口赋予的。其大量使用了 Java8 引入的函数式编程。</p>
<h2 id="CompletableFuture-常见操作"><a href="#CompletableFuture-常见操作" class="headerlink" title="CompletableFuture 常见操作"></a>CompletableFuture 常见操作</h2><h3 id="创建-CompletableFuture"><a href="#创建-CompletableFuture" class="headerlink" title="创建 CompletableFuture"></a>创建 CompletableFuture</h3><p>常见的创建 <code>CompletableFuture</code> 对象的方法如下：</p>
<ol>
<li>通过 new 关键字。</li>
<li>基于 <code>CompletableFuture</code> 自带的静态工厂方法：<code>runAsync()</code>、<code>supplyAsync()</code> 。</li>
</ol>
<h4 id="new-关键字"><a href="#new-关键字" class="headerlink" title="new 关键字"></a>new 关键字</h4><p>通过 new 关键字创建 <code>CompletableFuture</code> 对象这种使用方式可以看作是将 <code>CompletableFuture</code> 当做 <code>Future</code> 来使用。</p>
<p>下面咱们来看一个简单的案例。</p>
<p>我们通过创建了一个结果值类型为 <code>RpcResponse&lt;Object&gt;</code> 的 <code>CompletableFuture</code>，你可以把 <code>resultFuture</code> 看作是异步运算结果的载体。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;RpcResponse&lt;Object&gt;&gt; resultFuture = <span class="hljs-keyword">new</span> <span class="hljs-title class_">CompletableFuture</span>&lt;&gt;();<br></code></pre></td></tr></table></figure>



<p>你可以通过 <code>isDone()</code> 方法来检查是否已经完成。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">isDone</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-keyword">return</span> result != <span class="hljs-literal">null</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<p>获取异步计算的结果也非常简单，直接调用 <code>get()</code> 方法即可。调用 <code>get()</code> 方法的线程会阻塞直到 <code>CompletableFuture</code> 完成运算。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs java">rpcResponse = completableFuture.get();<br></code></pre></td></tr></table></figure>


<p>假设在未来的某个时刻，我们得到了最终的结果。这时，我们可以调用 <code>complete()</code> 方法为其传入结果，这表示 <code>resultFuture</code> 已经被完成了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// complete() 方法只能调用一次，后续调用将被忽略。</span><br>resultFuture.complete(rpcResponse);<br></code></pre></td></tr></table></figure>



<p>如果你已经知道计算的结果的话，可以使用静态方法 <code>completedFuture()</code> 来创建 <code>CompletableFuture</code> 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.completedFuture(<span class="hljs-string">&quot;hello!&quot;</span>);<br>assertEquals(<span class="hljs-string">&quot;hello!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p><code>completedFuture()</code> 方法底层调用的是带参数的 new 方法，只不过，这个方法不对外暴露。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">completedFuture</span><span class="hljs-params">(U value)</span> &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">CompletableFuture</span>&lt;U&gt;((value == <span class="hljs-literal">null</span>) ? NIL : value);<br>&#125;<br></code></pre></td></tr></table></figure>



<h4 id="静态工厂方法"><a href="#静态工厂方法" class="headerlink" title="静态工厂方法"></a>静态工厂方法</h4><p>这两个方法可以帮助我们封装计算逻辑。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">supplyAsync</span><span class="hljs-params">(Supplier&lt;U&gt; supplier)</span>;<br><span class="hljs-comment">// 使用自定义线程池(推荐)</span><br><span class="hljs-keyword">static</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">supplyAsync</span><span class="hljs-params">(Supplier&lt;U&gt; supplier, Executor executor)</span>;<br><span class="hljs-keyword">static</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">runAsync</span><span class="hljs-params">(Runnable runnable)</span>;<br><span class="hljs-comment">// 使用自定义线程池(推荐)</span><br><span class="hljs-keyword">static</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">runAsync</span><span class="hljs-params">(Runnable runnable, Executor executor)</span>;<br></code></pre></td></tr></table></figure>



<p><code>runAsync()</code> 方法接受的参数是 <code>Runnable</code> ，这是一个函数式接口，不允许返回值。当你需要异步操作且不关心返回结果的时候可以使用 <code>runAsync()</code> 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@FunctionalInterface</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Runnable</span> &#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>supplyAsync()</code> 方法接受的参数是 <code>Supplier&lt;T&gt;</code> ，这也是一个函数式接口，<code>T</code> 是返回结果值的类型。当你需要异步操作且关心返回结果的时候,可以使用 <code>supplyAsync()</code> 方法。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@FunctionalInterface</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Supplier</span>&lt;T&gt; &#123;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * Gets a result.</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> a result</span><br><span class="hljs-comment">     */</span><br>    T <span class="hljs-title function_">get</span><span class="hljs-params">()</span>;<br>&#125;<br></code></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;Void&gt; future = CompletableFuture.runAsync(() -&gt; System.out.println(<span class="hljs-string">&quot;hello!&quot;</span>));<br>future.get();<span class="hljs-comment">// 输出 &quot;hello!&quot;</span><br>CompletableFuture&lt;String&gt; future2 = CompletableFuture.supplyAsync(() -&gt; <span class="hljs-string">&quot;hello!&quot;</span>);<br>assertEquals(<span class="hljs-string">&quot;hello!&quot;</span>, future2.get());<br></code></pre></td></tr></table></figure>



<h3 id="处理异步结算的结果"><a href="#处理异步结算的结果" class="headerlink" title="处理异步结算的结果"></a>处理异步结算的结果</h3><p>当我们获取到异步计算的结果之后，还可以对其进行进一步的处理，比较常用的方法有下面几个：</p>
<ul>
<li><code>thenApply()</code></li>
<li><code>thenAccept()</code></li>
<li><code>thenRun()</code></li>
<li><code>whenComplete()</code></li>
</ul>
<p><code>thenApply()</code> 方法接受一个 <code>Function</code> 实例，用它来处理结果。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 沿用上一个任务的线程池</span><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenApply</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T,? extends U&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniApplyStage(<span class="hljs-literal">null</span>, fn);<br>&#125;<br><br><span class="hljs-comment">//使用默认的 ForkJoinPool 线程池（不推荐）</span><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenApplyAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T,? extends U&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniApplyStage(defaultExecutor(), fn);<br>&#125;<br><span class="hljs-comment">// 使用自定义线程池(推荐)</span><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenApplyAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T,? extends U&gt; fn, Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniApplyStage(screenExecutor(executor), fn);<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>thenApply()</code> 方法使用示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.completedFuture(<span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenApply(s -&gt; s + <span class="hljs-string">&quot;world!&quot;</span>);<br>assertEquals(<span class="hljs-string">&quot;hello!world!&quot;</span>, future.get());<br><span class="hljs-comment">// 这次调用将被忽略。（为啥呢？）</span><br>future.thenApply(s -&gt; s + <span class="hljs-string">&quot;nice!&quot;</span>);<br>assertEquals(<span class="hljs-string">&quot;hello!world!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p>你还可以进行 <strong>流式调用</strong>：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.completedFuture(<span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenApply(s -&gt; s + <span class="hljs-string">&quot;world!&quot;</span>).thenApply(s -&gt; s + <span class="hljs-string">&quot;nice!&quot;</span>);<br>assertEquals(<span class="hljs-string">&quot;hello!world!nice!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p><strong>如果你不需要从回调函数中获取返回结果，可以使用 <code>thenAccept()</code> 或者 <code>thenRun()</code>。这两个方法的区别在于 <code>thenRun()</code> 不能访问异步计算的结果。</strong></p>
<p><code>thenAccept()</code> 方法的参数是 <code>Consumer&lt;? super T&gt;</code> 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenAccept</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniAcceptStage(<span class="hljs-literal">null</span>, action);<br>&#125;<br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenAcceptAsync</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniAcceptStage(defaultExecutor(), action);<br>&#125;<br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenAcceptAsync</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; action, Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniAcceptStage(screenExecutor(executor), action);<br>&#125;<br></code></pre></td></tr></table></figure>



<p>顾名思义，<code>Consumer</code> 属于消费型接口，它可以接收 1 个输入对象然后进行“消费”。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@FunctionalInterface</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">Consumer</span>&lt;T&gt; &#123;<br><br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">accept</span><span class="hljs-params">(T t)</span>;<br><br>    <span class="hljs-keyword">default</span> Consumer&lt;T&gt; <span class="hljs-title function_">andThen</span><span class="hljs-params">(Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; after)</span> &#123;<br>        Objects.requireNonNull(after);<br>        <span class="hljs-keyword">return</span> (T t) -&gt; &#123; accept(t); after.accept(t); &#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>thenRun()</code> 的方法的参数是 <code>Runnable</code> 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenRun</span><span class="hljs-params">(Runnable action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniRunStage(<span class="hljs-literal">null</span>, action);<br>&#125;<br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenRunAsync</span><span class="hljs-params">(Runnable action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniRunStage(defaultExecutor(), action);<br>&#125;<br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">thenRunAsync</span><span class="hljs-params">(Runnable action, Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniRunStage(screenExecutor(executor), action);<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>thenAccept()</code> 和 <code>thenRun()</code> 使用示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture.completedFuture(<span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenApply(s -&gt; s + <span class="hljs-string">&quot;world!&quot;</span>).thenApply(s -&gt; s + <span class="hljs-string">&quot;nice!&quot;</span>).thenAccept(System.out::println);<span class="hljs-comment">//hello!world!nice!</span><br><br>CompletableFuture.completedFuture(<span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenApply(s -&gt; s + <span class="hljs-string">&quot;world!&quot;</span>).thenApply(s -&gt; s + <span class="hljs-string">&quot;nice!&quot;</span>).thenRun(() -&gt; System.out.println(<span class="hljs-string">&quot;hello!&quot;</span>));<span class="hljs-comment">//hello!</span><br></code></pre></td></tr></table></figure>



<p><code>whenComplete()</code> 的方法的参数是 <code>BiConsumer&lt;? super T, ? super Throwable&gt;</code> 。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> CompletableFuture&lt;T&gt; <span class="hljs-title function_">whenComplete</span><span class="hljs-params">(</span><br><span class="hljs-params">    BiConsumer&lt;? <span class="hljs-built_in">super</span> T, ? <span class="hljs-built_in">super</span> Throwable&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniWhenCompleteStage(<span class="hljs-literal">null</span>, action);<br>&#125;<br><br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;T&gt; <span class="hljs-title function_">whenCompleteAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    BiConsumer&lt;? <span class="hljs-built_in">super</span> T, ? <span class="hljs-built_in">super</span> Throwable&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniWhenCompleteStage(defaultExecutor(), action);<br>&#125;<br><span class="hljs-comment">// 使用自定义线程池(推荐)</span><br><span class="hljs-keyword">public</span> CompletableFuture&lt;T&gt; <span class="hljs-title function_">whenCompleteAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    BiConsumer&lt;? <span class="hljs-built_in">super</span> T, ? <span class="hljs-built_in">super</span> Throwable&gt; action, Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniWhenCompleteStage(screenExecutor(executor), action);<br>&#125;<br></code></pre></td></tr></table></figure>



<p>相对于 <code>Consumer</code> ， <code>BiConsumer</code> 可以接收 2 个输入对象然后进行“消费”。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@FunctionalInterface</span><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title class_">BiConsumer</span>&lt;T, U&gt; &#123;<br>    <span class="hljs-keyword">void</span> <span class="hljs-title function_">accept</span><span class="hljs-params">(T t, U u)</span>;<br><br>    <span class="hljs-keyword">default</span> BiConsumer&lt;T, U&gt; <span class="hljs-title function_">andThen</span><span class="hljs-params">(BiConsumer&lt;? <span class="hljs-built_in">super</span> T, ? <span class="hljs-built_in">super</span> U&gt; after)</span> &#123;<br>        Objects.requireNonNull(after);<br><br>        <span class="hljs-keyword">return</span> (l, r) -&gt; &#123;<br>            accept(l, r);<br>            after.accept(l, r);<br>        &#125;;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>whenComplete()</code> 使用示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(() -&gt; <span class="hljs-string">&quot;hello!&quot;</span>)<br>        .whenComplete((res, ex) -&gt; &#123;<br>            <span class="hljs-comment">// res 代表返回的结果</span><br>            <span class="hljs-comment">// ex 的类型为 Throwable ，代表抛出的异常</span><br>            System.out.println(res);<br>            <span class="hljs-comment">// 这里没有抛出异常所以为 null</span><br>            assertNull(ex);<br>        &#125;);<br>assertEquals(<span class="hljs-string">&quot;hello!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<h3 id="异常处理"><a href="#异常处理" class="headerlink" title="异常处理"></a>异常处理</h3><p>你可以通过 <code>handle()</code> 方法来处理任务执行过程中可能出现的抛出异常的情况。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">handle</span><span class="hljs-params">(BiFunction&lt;? <span class="hljs-built_in">super</span> T, Throwable, ? extends U&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniHandleStage(<span class="hljs-literal">null</span>, fn);<br>&#125;<br><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">handleAsync</span><span class="hljs-params">(BiFunction&lt;? <span class="hljs-built_in">super</span> T, Throwable, ? extends U&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniHandleStage(defaultExecutor(), fn);<br>&#125;<br><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">handleAsync</span><span class="hljs-params">(BiFunction&lt;? <span class="hljs-built_in">super</span> T, Throwable, ? extends U&gt; fn, Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniHandleStage(screenExecutor(executor), fn);<br>&#125;<br></code></pre></td></tr></table></figure>

<p>示例代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) &#123;<br>        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">&quot;Computation error!&quot;</span>);<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;hello!&quot;</span>;<br>&#125;).handle((res, ex) -&gt; &#123;<br>    <span class="hljs-comment">// res 代表返回的结果</span><br>    <span class="hljs-comment">// ex 的类型为 Throwable ，代表抛出的异常</span><br>    <span class="hljs-keyword">return</span> res != <span class="hljs-literal">null</span> ? res : <span class="hljs-string">&quot;world!&quot;</span>;<br>&#125;);<br>assertEquals(<span class="hljs-string">&quot;world!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p>你还可以通过 <code>exceptionally()</code> 方法来处理异常情况。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future<br>        = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) &#123;<br>        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">&quot;Computation error!&quot;</span>);<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;hello!&quot;</span>;<br>&#125;).exceptionally(ex -&gt; &#123;<br>    System.out.println(ex.toString());<span class="hljs-comment">// CompletionException</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;world!&quot;</span>;<br>&#125;);<br>assertEquals(<span class="hljs-string">&quot;world!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p>如果你想让 <code>CompletableFuture</code> 的结果就是异常的话，可以使用 <code>completeExceptionally()</code> 方法为其赋值。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; completableFuture = <span class="hljs-keyword">new</span> <span class="hljs-title class_">CompletableFuture</span>&lt;&gt;();<br><span class="hljs-comment">// ...</span><br>completableFuture.completeExceptionally(<br>  <span class="hljs-keyword">new</span> <span class="hljs-title class_">RuntimeException</span>(<span class="hljs-string">&quot;Calculation failed!&quot;</span>));<br><span class="hljs-comment">// ...</span><br>completableFuture.get(); <span class="hljs-comment">// ExecutionException</span><br></code></pre></td></tr></table></figure>



<h3 id="组合-CompletableFuture"><a href="#组合-CompletableFuture" class="headerlink" title="组合 CompletableFuture"></a>组合 CompletableFuture</h3><p>你可以使用 <code>thenCompose()</code> 按顺序链接两个 <code>CompletableFuture</code> 对象，实现异步的任务链。它的作用是将前一个任务的返回结果作为下一个任务的输入参数，从而形成一个依赖关系。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenCompose</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T, ? extends CompletionStage&lt;U&gt;&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniComposeStage(<span class="hljs-literal">null</span>, fn);<br>&#125;<br><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenComposeAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T, ? extends CompletionStage&lt;U&gt;&gt; fn)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniComposeStage(defaultExecutor(), fn);<br>&#125;<br><br><span class="hljs-keyword">public</span> &lt;U&gt; CompletableFuture&lt;U&gt; <span class="hljs-title function_">thenComposeAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    Function&lt;? <span class="hljs-built_in">super</span> T, ? extends CompletionStage&lt;U&gt;&gt; fn,</span><br><span class="hljs-params">    Executor executor)</span> &#123;<br>    <span class="hljs-keyword">return</span> uniComposeStage(screenExecutor(executor), fn);<br>&#125;<br></code></pre></td></tr></table></figure>



<p><code>thenCompose()</code> 方法会使用示例如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; future<br>        = CompletableFuture.supplyAsync(() -&gt; <span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenCompose(s -&gt; CompletableFuture.supplyAsync(() -&gt; s + <span class="hljs-string">&quot;world!&quot;</span>));<br>assertEquals(<span class="hljs-string">&quot;hello!world!&quot;</span>, future.get());<br></code></pre></td></tr></table></figure>



<p>在实际开发中，这个方法还是非常有用的。比如说，task1 和 task2 都是异步执行的，但 task1 必须执行完成后才能开始执行 task2（task2 依赖 task1 的执行结果）。</p>
<p>和 <code>thenCompose()</code> 方法类似的还有 <code>thenCombine()</code> 方法， 它同样可以组合两个 <code>CompletableFuture</code> 对象。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; completableFuture<br>        = CompletableFuture.supplyAsync(() -&gt; <span class="hljs-string">&quot;hello!&quot;</span>)<br>        .thenCombine(CompletableFuture.supplyAsync(<br>                () -&gt; <span class="hljs-string">&quot;world!&quot;</span>), (s1, s2) -&gt; s1 + s2)<br>        .thenCompose(s -&gt; CompletableFuture.supplyAsync(() -&gt; s + <span class="hljs-string">&quot;nice!&quot;</span>));<br>assertEquals(<span class="hljs-string">&quot;hello!world!nice!&quot;</span>, completableFuture.get());<br></code></pre></td></tr></table></figure>



<p><strong>那 <code>thenCompose()</code> 和 <code>thenCombine()</code> 有什么区别呢？</strong></p>
<ul>
<li><code>thenCompose()</code> 可以链接两个 <code>CompletableFuture</code> 对象，并将前一个任务的返回结果作为下一个任务的参数，它们之间存在着先后顺序。</li>
<li><code>thenCombine()</code> 会在两个任务都执行完成后，把两个任务的结果合并。两个任务是并行执行的，它们之间并没有先后依赖顺序。</li>
</ul>
<p>除了 <code>thenCompose()</code> 和 <code>thenCombine()</code> 之外， 还有一些其他的组合 <code>CompletableFuture</code> 的方法用于实现不同的效果，满足不同的业务需求。</p>
<p>例如，如果我们想要实现 task1 和 task2 中的任意一个任务执行完后就执行 task3 的话，可以使用 <code>acceptEither()</code>。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">acceptEither</span><span class="hljs-params">(</span><br><span class="hljs-params">    CompletionStage&lt;? extends T&gt; other, Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> orAcceptStage(<span class="hljs-literal">null</span>, other, action);<br>&#125;<br><br><span class="hljs-keyword">public</span> CompletableFuture&lt;Void&gt; <span class="hljs-title function_">acceptEitherAsync</span><span class="hljs-params">(</span><br><span class="hljs-params">    CompletionStage&lt;? extends T&gt; other, Consumer&lt;? <span class="hljs-built_in">super</span> T&gt; action)</span> &#123;<br>    <span class="hljs-keyword">return</span> orAcceptStage(asyncPool, other, action);<br>&#125;<br></code></pre></td></tr></table></figure>



<p>简单举一个例子：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;String&gt; task = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;任务1开始执行，当前时间：&quot;</span> + System.currentTimeMillis());<br>    <span class="hljs-keyword">try</span> &#123;<br>        Thread.sleep(<span class="hljs-number">500</span>);<br>    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>        e.printStackTrace();<br>    &#125;<br>    System.out.println(<span class="hljs-string">&quot;任务1执行完毕，当前时间：&quot;</span> + System.currentTimeMillis());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task1&quot;</span>;<br>&#125;);<br><br>CompletableFuture&lt;String&gt; task2 = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;任务2开始执行，当前时间：&quot;</span> + System.currentTimeMillis());<br>    <span class="hljs-keyword">try</span> &#123;<br>        Thread.sleep(<span class="hljs-number">1000</span>);<br>    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>        e.printStackTrace();<br>    &#125;<br>    System.out.println(<span class="hljs-string">&quot;任务2执行完毕，当前时间：&quot;</span> + System.currentTimeMillis());<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;task2&quot;</span>;<br>&#125;);<br><br>task.acceptEitherAsync(task2, (res) -&gt; &#123;<br>    System.out.println(<span class="hljs-string">&quot;任务3开始执行，当前时间：&quot;</span> + System.currentTimeMillis());<br>    System.out.println(<span class="hljs-string">&quot;上一个任务的结果为：&quot;</span> + res);<br>&#125;);<br><br><span class="hljs-comment">// 增加一些延迟时间，确保异步任务有足够的时间完成</span><br><span class="hljs-keyword">try</span> &#123;<br>    Thread.sleep(<span class="hljs-number">2000</span>);<br>&#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>    e.printStackTrace();<br>&#125;<br></code></pre></td></tr></table></figure>



<p>输出：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs text">任务1开始执行，当前时间：1695088058520<br>任务2开始执行，当前时间：1695088058521<br>任务1执行完毕，当前时间：1695088059023<br>任务3开始执行，当前时间：1695088059023<br>上一个任务的结果为：task1<br>任务2执行完毕，当前时间：1695088059523<br></code></pre></td></tr></table></figure>

<p>任务组合操作<code>acceptEitherAsync()</code>会在异步任务 1 和异步任务 2 中的任意一个完成时触发执行任务 3，但是需要注意，这个触发时机是不确定的。如果任务 1 和任务 2 都还未完成，那么任务 3 就不能被执行。</p>
<h3 id="并行运行多个-CompletableFuture"><a href="#并行运行多个-CompletableFuture" class="headerlink" title="并行运行多个 CompletableFuture"></a>并行运行多个 CompletableFuture</h3><p>你可以通过 <code>CompletableFuture</code> 的 <code>allOf()</code>这个静态方法来并行运行多个 <code>CompletableFuture</code> 。</p>
<p>实际项目中，我们经常需要并行运行多个互不相关的任务，这些任务之间没有依赖关系，可以互相独立地运行。</p>
<p>比说我们要读取处理 6 个文件，这 6 个任务都是没有执行顺序依赖的任务，但是我们需要返回给用户的时候将这几个文件的处理的结果进行统计整理。像这种情况我们就可以使用并行运行多个 <code>CompletableFuture</code> 来处理。</p>
<p>示例代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;Void&gt; task1 =<br>  CompletableFuture.supplyAsync(()-&gt;&#123;<br>    <span class="hljs-comment">//自定义业务操作</span><br>  &#125;);<br>......<br>CompletableFuture&lt;Void&gt; task6 =<br>  CompletableFuture.supplyAsync(()-&gt;&#123;<br>    <span class="hljs-comment">//自定义业务操作</span><br>  &#125;);<br>......<br> CompletableFuture&lt;Void&gt; headerFuture=CompletableFuture.allOf(task1,.....,task6);<br><br>  <span class="hljs-keyword">try</span> &#123;<br>    headerFuture.join();<br>  &#125; <span class="hljs-keyword">catch</span> (Exception ex) &#123;<br>    ......<br>  &#125;<br>System.out.println(<span class="hljs-string">&quot;all done. &quot;</span>);<br></code></pre></td></tr></table></figure>

<p>经常和 <code>allOf()</code> 方法拿来对比的是 <code>anyOf()</code> 方法。</p>
<p><strong><code>allOf()</code> 方法会等到所有的 <code>CompletableFuture</code> 都运行完成之后再返回</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-type">Random</span> <span class="hljs-variable">rand</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Random</span>();<br>CompletableFuture&lt;String&gt; future1 = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    <span class="hljs-keyword">try</span> &#123;<br>        Thread.sleep(<span class="hljs-number">1000</span> + rand.nextInt(<span class="hljs-number">1000</span>));<br>    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>        e.printStackTrace();<br>    &#125; <span class="hljs-keyword">finally</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;future1 done...&quot;</span>);<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;abc&quot;</span>;<br>&#125;);<br>CompletableFuture&lt;String&gt; future2 = CompletableFuture.supplyAsync(() -&gt; &#123;<br>    <span class="hljs-keyword">try</span> &#123;<br>        Thread.sleep(<span class="hljs-number">1000</span> + rand.nextInt(<span class="hljs-number">1000</span>));<br>    &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>        e.printStackTrace();<br>    &#125; <span class="hljs-keyword">finally</span> &#123;<br>        System.out.println(<span class="hljs-string">&quot;future2 done...&quot;</span>);<br>    &#125;<br>    <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;efg&quot;</span>;<br>&#125;);<br></code></pre></td></tr></table></figure>



<p>调用 <code>join()</code> 可以让程序等<code>future1</code> 和 <code>future2</code> 都运行完了之后再继续执行。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;Void&gt; completableFuture = CompletableFuture.allOf(future1, future2);<br>completableFuture.join();<br>assertTrue(completableFuture.isDone());<br>System.out.println(<span class="hljs-string">&quot;all futures done...&quot;</span>);<br></code></pre></td></tr></table></figure>

<p>输出：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java">future1 done...<br>future2 done...<br>all futures done...<br></code></pre></td></tr></table></figure>



<p><strong><code>anyOf()</code> 方法不会等待所有的 <code>CompletableFuture</code> 都运行完成之后再返回，只要有一个执行完成即可！</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java">CompletableFuture&lt;Object&gt; f = CompletableFuture.anyOf(future1, future2);<br>System.out.println(f.get());<br></code></pre></td></tr></table></figure>

<p>输出结果可能是：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java">future2 done...<br>efg<br></code></pre></td></tr></table></figure>

<p>也可能是：</p>
<figure class="highlight text"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs text">future1 done...<br>abc<br></code></pre></td></tr></table></figure>



<h2 id="CompletableFuture-使用建议"><a href="#CompletableFuture-使用建议" class="headerlink" title="CompletableFuture 使用建议"></a>CompletableFuture 使用建议</h2><h3 id="使用自定义线程池"><a href="#使用自定义线程池" class="headerlink" title="使用自定义线程池"></a>使用自定义线程池</h3><p><code>CompletableFuture</code> 默认使用<code>ForkJoinPool.commonPool()</code> 作为执行器，这个线程池是全局共享的，可能会被其他任务占用，导致性能下降或者饥饿。因此，建议使用自定义的线程池来执行 <code>CompletableFuture</code> 的异步任务，可以提高并发度和灵活性。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">private</span> <span class="hljs-type">ThreadPoolExecutor</span> <span class="hljs-variable">executor</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ThreadPoolExecutor</span>(<span class="hljs-number">10</span>, <span class="hljs-number">10</span>,<br>        <span class="hljs-number">0L</span>, TimeUnit.MILLISECONDS,<br>        <span class="hljs-keyword">new</span> <span class="hljs-title class_">LinkedBlockingQueue</span>&lt;Runnable&gt;());<br><br>CompletableFuture.runAsync(() -&gt; &#123;<br> 		<span class="hljs-comment">//...</span><br>&#125;, executor);<br></code></pre></td></tr></table></figure>



<h3 id="尽量避免使用-get"><a href="#尽量避免使用-get" class="headerlink" title="尽量避免使用 get()"></a>尽量避免使用 get()</h3><p><code>CompletableFuture</code>的<code>get()</code>方法是阻塞的，尽量避免使用。如果必须要使用的话，需要添加超时时间，否则可能会导致主线程一直等待，无法执行其他任务。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs java">    CompletableFuture&lt;String&gt; future = CompletableFuture.supplyAsync(() -&gt; &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            Thread.sleep(<span class="hljs-number">10_000</span>);<br>        &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>            e.printStackTrace();<br>        &#125;<br>        <span class="hljs-keyword">return</span> <span class="hljs-string">&quot;Hello, world!&quot;</span>;<br>    &#125;);<br><br>    <span class="hljs-comment">// 获取异步任务的返回值，设置超时时间为 5 秒</span><br>    <span class="hljs-keyword">try</span> &#123;<br>        <span class="hljs-type">String</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> future.get(<span class="hljs-number">5</span>, TimeUnit.SECONDS);<br>        System.out.println(result);<br>    &#125; <span class="hljs-keyword">catch</span> (InterruptedException | ExecutionException | TimeoutException e) &#123;<br>        <span class="hljs-comment">// 处理异常</span><br>        e.printStackTrace();<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>上面这段代码在调用 <code>get()</code> 时抛出了 <code>TimeoutException</code> 异常。这样我们就可以在异常处理中进行相应的操作，比如取消任务、重试任务、记录日志等。</p>
<h3 id="正确进行异常处理"><a href="#正确进行异常处理" class="headerlink" title="正确进行异常处理"></a>正确进行异常处理</h3><ul>
<li>使用 <code>whenComplete</code> 方法可以在任务完成时触发回调函数，并正确地处理异常，而不是让异常被吞噬或丢失。</li>
<li>使用 <code>exceptionally</code> 方法可以处理异常并重新抛出，以便异常能够传播到后续阶段，而不是让异常被忽略或终止。</li>
<li>使用 <code>handle</code> 方法可以处理正常的返回结果和异常，并返回一个新的结果，而不是让异常影响正常的业务逻辑。</li>
<li>使用 <code>CompletableFuture.allOf</code> 方法可以组合多个 <code>CompletableFuture</code>，并统一处理所有任务的异常，而不是让异常处理过于冗长或重复。</li>
</ul>
<h3 id="合理组合多个异步任务"><a href="#合理组合多个异步任务" class="headerlink" title="合理组合多个异步任务"></a>合理组合多个异步任务</h3><p>正确使用 <code>thenCompose()</code> 、 <code>thenCombine()</code> 、<code>acceptEither()</code>、<code>allOf()</code>、<code>anyOf() </code>等方法来组合多个异步任务，以满足实际业务的需求，提高程序执行效率。</p>
<p><img src="C:\Users\69425\AppData\Roaming\Typora\typora-user-images\image-20231015211855815.png" srcset="/img/loading.gif" lazyload alt="image-20231015211855815"></p>
<h4 id="Callable-和-Future-有什么关系？"><a href="#Callable-和-Future-有什么关系？" class="headerlink" title="Callable 和 Future 有什么关系？"></a>Callable 和 Future 有什么关系？</h4><p>我们可以通过 <code>FutureTask</code> 来理解 <code>Callable</code> 和 <code>Future</code> 之间的关系。</p>
<p><code>FutureTask</code> 提供了 <code>Future</code> 接口的基本实现，常用来封装 <code>Callable</code> 和 <code>Runnable</code>，具有取消任务、查看任务是否执行完成以及获取任务执行结果的方法。<code>ExecutorService.submit()</code> 方法返回的其实就是 <code>Future</code> 的实现类 <code>FutureTask</code> 。</p>
<figure class="highlight bnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs bnf"><span class="hljs-attribute">&lt;T&gt;</span> Future<span class="hljs-attribute">&lt;T&gt;</span> submit(Callable<span class="hljs-attribute">&lt;T&gt;</span> task);<br>Future<span class="hljs-attribute">&lt;?&gt;</span> submit(Runnable task);<br></code></pre></td></tr></table></figure>

<p><code>FutureTask</code> 不光实现了 <code>Future</code>接口，还实现了<code>Runnable</code> 接口，因此可以作为任务直接被线程执行。</p>
<p><code>FutureTask</code> 有两个构造函数，可传入 <code>Callable</code> 或者 <code>Runnable</code> 对象。实际上，传入 <code>Runnable</code> 对象也会在方法内部转换为<code>Callable</code> 对象。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">public</span> FutureTask(Callable&lt;V&gt; callable) &#123;<br>        <span class="hljs-keyword">if</span> (callable == <span class="hljs-literal">null</span>)<br>                <span class="hljs-keyword">throw</span> new NullPointerException();<br>        <span class="hljs-keyword">this</span>.callable = callable;<br>        <span class="hljs-keyword">this</span>.state = NEW;<br>&#125;<br><span class="hljs-keyword">public</span> FutureTask(Runnable runnable, V result) &#123;<br>        <span class="hljs-comment">// 通过适配器RunnableAdapter来将Runnable对象runnable转换成Callable对象</span><br>        <span class="hljs-keyword">this</span>.callable = Executors.callable(runnable, result);<br>        <span class="hljs-keyword">this</span>.state = NEW;<br>&#125;<br></code></pre></td></tr></table></figure>

<p><code>FutureTask</code>相当于对<code>Callable</code> 进行了封装，管理着任务执行的情况，存储了 <code>Callable</code> 的 <code>call</code> 方法的任务执行结果。</p>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/JUC/" class="category-chain-item">JUC</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/JUC/" class="print-no-link">#JUC</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>CompletableFuture</div>
      <div>http://example.com/2021/04/06/JUC/CompletableFuture/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>fyy-coding</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年4月6日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/04/06/JUC/CAS%E7%AE%97%E6%B3%95/" title="CAS算法">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">CAS算法</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/04/06/JUC/ReentrantLock/" title="ReentrantLock">
                        <span class="hidden-mobile">ReentrantLock</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"ufph8TbmK43d1JfQxLvss4KY-MdYXbMMI","appKey":"96APiPOtZEiCQlv5h3jjZfbC","path":"window.location.pathname","placeholder":null,"avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="leancloud-site-pv-container" style="display: none">
        总访问量
        <span id="leancloud-site-pv"></span>
        次
      </span>
    
    
      <span id="leancloud-site-uv-container" style="display: none">
        总访客数
        <span id="leancloud-site-uv"></span>
        人
      </span>
    
    

  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script defer src="/js/leancloud.js" ></script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
